package middleware

import (
	"im/internal/common"
	"net/http"

	"github.com/gin-gonic/gin"
)

// ResponseHandler 捕获正常放回
// . "im/internal/common"
// Response(Error("成功消息"))
// Response(Success("失败消息"))
func ResponseHandler() gin.HandlerFunc {
	return func(c *gin.Context) {
		defer func() {
			if err := recover(); err != nil {
				// 检查是否是 Result 类型
				if result, ok := err.(*common.Result); ok {
					c.JSON(http.StatusOK, result)
				} else {
					// 如果不是 Result 类型，则返回内部错误
					c.JSON(http.StatusInternalServerError, common.Error("Internal Server Error"))
				}
				c.Abort()
			}
		}()

		c.Next()
	}
}
